<template>
  <div id="applyConsult">
    <el-form :model="applyForm" :rules="rules" label-position="top" ref="formRef">
      <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 20px" v-if="!isComponent">
        <span>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>我的会诊</el-breadcrumb-item>
            <el-breadcrumb-item>新建申请</el-breadcrumb-item>
          </el-breadcrumb>
        </span>
        <el-button icon="arrow-left" size="mini" type="primary" @click="backTo">返回</el-button>
      </div>
      <div>
        <el-divider content-position="left">会诊信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="申请医生：" prop="doctorId">
              <el-input v-model="applyForm.doctorName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注：" prop="remarks">
              <el-input type="textarea" :maxlength="100" show-word-limit v-model="applyForm.remarks"> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="会诊科室：" prop="departmentId">
              <el-select
                  @change="handleGetDoctorList"
                  v-model="applyForm.departmentId"
                  placeholder="科室名称">
                <el-option v-for="item in hospitalDeptOptions" :key="item.id" :label="item.departmentName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="会诊专家：" prop="expertDoctorId">
              <el-select
                  filterable
                  multiple
                  v-model="applyForm.expertDoctorId"
                  placeholder="医生">
                <el-option v-for="item in doctorList" :key="item.id" :label="item.trueName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-divider content-position="left">患者信息</el-divider>
        <el-row type="flex" :gutter="20">
          <el-col>
            <el-form-item label="身份证号：" prop="patientIdcard">
              <el-input v-model="applyForm.patientIdcard">
                <el-button slot="append" icon="el-icon-search" @click="openHistory">查询</el-button>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="姓名：" prop="inquiryPatientName">
              <el-input v-model="applyForm.inquiryPatientName"> </el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="性别" prop="inquiryPatientSex">
              <el-select v-model="applyForm.inquiryPatientSex">
                <el-option :value="1" label="男"></el-option>
                <el-option :value="0" label="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="年龄：" prop="inquiryPatientAge">
              <el-input v-model="applyForm.inquiryPatientAge"> </el-input>

            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" :gutter="20">
          <el-col>
            <el-form-item label="身高(cm)：" prop="inquiryPatientMeasured.patientHeight">
              <el-input v-model="applyForm.inquiryPatientMeasured.patientHeight"> </el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="体重(kg)：" prop="inquiryPatientMeasured.patientWeight">
              <el-input v-model="applyForm.inquiryPatientMeasured.patientWeight"> </el-input>

            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="血糖(mmol/l)：" prop="inquiryPatientMeasured.dataGlu">
              <el-input v-model="applyForm.inquiryPatientMeasured.dataGlu"> </el-input>

            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="体温(°C)：" prop="inquiryPatientMeasured.dataAnimalHeat">
              <el-input v-model="applyForm.inquiryPatientMeasured.dataAnimalHeat"> </el-input>

            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-divider content-position="left">疾病信息</el-divider>
        <el-row type="flex" :gutter="20">
          <el-col :span="6">
            <el-form-item label="目前诊断：" prop="diagnosis">
              <el-select filterable multiple v-model="applyForm.diagnosis" value-key="diagnosisId">
                <el-option v-for="item in diagnosisList" :key="item.diagnosisId" :label="item.diagnosis" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主诉：" prop="mainSuit">
              <el-input type="textarea" v-model="applyForm.mainSuit" :maxlength="50" show-word-limit> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" :gutter="20">
          <el-col :span="6">
            <el-form-item label="现病史：" prop="presentIllness">
              <el-input type="textarea" v-model="applyForm.presentIllness" :maxlength="50" show-word-limit> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="既往史：" prop="historyPresentIllness">
              <el-input type="textarea" v-model="applyForm.historyPresentIllness" :maxlength="50" show-word-limit> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="会诊目的：" prop="rcsPurpose">
              <el-input type="textarea" v-model="applyForm.rcsPurpose" :maxlength="50" show-word-limit> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片资料：" prop="doctor">
          <ImageUpload
              ref="uploadPic"
              :upload-params="ossParams"
              :multiple="true"
              :img-url="imageUrl"
              @change="val => handleChangeUpload(val, 'imageUrl')"></ImageUpload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </div>
    </el-form>
    <div>
      <el-button style="width: 200px;" round type="primary" @click="submit"
        >提交</el-button
      >
    </div>
  </div>
</template>

<script>

import ImageUpload from '@/components/image-upload/image-upload';

export default {
  components: {
    ImageUpload,
  },
  data() {
    return {
      ossParams: '',
      imageUrl: [],
      /**
       * 表单
       */
      trueName: this.$authInfo.getUser().trueName,
      applyForm: {
        inquiryLogId: '',
        inquiryPatientId: '',
        userId: '',
        hospitalId: '',
        doctorId: '',
        doctorName: '',
        expertDoctorId: [],
        patientIdcard: '',
        inquiryPatientMeasured: {
          patientHeight: '',
          patientWeight: '',
          dataAnimalHeat: '',
          dataGlu: '',
        },
        inquiryPatientSex: '',
        inquiryPatientAge: '',
        inquiryPatientPhone: '',
        diagnosis: [],
        mainSuit: '',
        presentIllness: '',
        historyPresentIllness: '',
        rcsPurpose: '',
        remarks: '',
        files: '',
        status: 1,
      },
      diagnosisList: [],
      rules: {
        doctorId: [{ required: true, message: '请选择申请医生', trigger: 'change' }],
        expertDoctorId: [{ required: true, message: '请选择会诊医生', trigger: 'change' }],
        patientIdcard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        patientHeight: [{ required: true, message: '请输入身高', trigger: 'blur' }],
        patientWeight: [{ required: true, message: '请输入体重', trigger: 'blur' }],
        inquiryPatientName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        inquiryPatientSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        inquiryPatientAge: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        diagnosis: [{ required: true, message: '请输入目前诊断', trigger: 'blur' }],
        mainSuit: [{ required: true, message: '请输入主诉', trigger: 'blur' }],
        presentIllness: [{ required: true, message: '请输入现病史', trigger: 'blur' }],
        historyPresentIllness: [{ required: true, message: '请输入既往史', trigger: 'blur' }],
        rcsPurpose: [{ required: true, message: '请输入会诊目的', trigger: 'blur' }],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      dialogHistory: false,
      historyList: [
      ],
      doctorList: [],
      hospitalDeptOptions: [],
      fileList: [],
      // 患者信息
      patientDetail: {},
    };
  },
  props: {
    applyQuery: {
      type: Object,
      default: () => ({}),
    },
    isComponent: {
      type: Boolean,
      default: false,
    },
    patientList: {
      type: Object,
      default: () => {},
    },
  },
  created() {
    this.applyForm.doctorId = this.$authInfo.getUser().id;
    this.applyForm.doctorName = this.$authInfo.getUser().trueName;
    // 获取带过来得患者信息
    this.getPatientInfo();
    this.init();
  },
  computed: {
    queryData() {
      return {
        ...this.$route.query,
        ...this.applyQuery,
      };
    },
  },
  methods: {
    handleChangeUpload(val) {
      this.imageUrl = val;
    },
    // 初始化
    init() {
      // 获取医生
      this.$ajax.getInquiryDoctorInfo({
        webToken: this.$authInfo.webToken(),
        id: this.$authInfo.getUser().id,
      }).then((res) => {
        this.applyForm.hospitalId = res.data.hospitalId;
      }).catch(() => {
        this.loading = false;
      });
      // 获取科室
      this.$ajax.getDepartmentListPc().then((res) => {
        this.hospitalDeptOptions = res.data.list;
        // 存在选中第一个
        if (this.hospitalDeptOptions.length) {
          this.applyForm.departmentId = this.hospitalDeptOptions[0].id;
          this.handleGetDoctorList();
        }
      });
      // 获取oss参数
      this.$ajax
        .uploadFileBridge({
          dir: 'webpc/',
        })
        .then((res) => {
          const { code, data } = res;
          if (code === 1) {
            console.log(data);
            this.ossParams = JSON.stringify(data);
          }
        })
        .catch((err) => {
          this.$util.message(err.msg);
        });

      this.$ajax.getIcdList({
        webToken: this.$authInfo.webToken(),
      }).then((res) => {
        this.diagnosisList = res.data.list.map(item => ({
          diagnosis: item.icdName,
          diagnosisId: item.id,
        }));
        console.log(res);
      }).catch((err) => {

      });
    },
    // 获取患者信息
    getPatientInfo() {
      if (!this.queryData.logId) return;
      this.applyForm.inquiryLogId = this.queryData.logId;
      // 获取患者信息
      const para = {
        id: this.queryData.logId,
        webToken: this.$authInfo.webToken(),
      };
      this.$ajax
        .getAllInfo(para)
        .then((res) => {
          this.setPatientInfo(res);
        })
        .catch((err) => {});
    },
    setPatientInfo(res) {
      this.patientDetail = res.data || {};
      this.applyForm.patientIdcard = res.data.patientIdcard;
      this.applyForm.inquiryPatientName = res.data.patientName;
      this.applyForm.inquiryPatientSex = res.data.patientSex;
      this.applyForm.inquiryPatientAge = res.data.patientAge;
      this.applyForm.inquiryPatientMeasured.dataAnimalHeat = res.data.dataAnimalHeat;
      this.applyForm.inquiryPatientMeasured.patientHeight = res.data.patientHeight;
      this.applyForm.inquiryPatientMeasured.patientWeight = res.data.patientWeight;
      this.applyForm.inquiryPatientMeasured.dataGlu = res.data.dataGlu;
      this.applyForm.userId = res.data.userId;
      this.applyForm.inquiryPatientId = res.data.id;

      this.diagnosisList.forEach((item) => {
        if (this.patientList.diagnosisList.find(_item => _item.diagnosis == item.diagnosis)) {
          this.applyForm.diagnosis.push(item);
        }
      });
      this.applyForm.mainSuit = this.patientList.mainSuit;
      this.applyForm.presentIllness = this.patientList.presentIllness;
      this.applyForm.historyPresentIllness = this.patientList.historyPresentIllness;
    },
    // 根据科室获取医生
    handleGetDoctorList() {
      this.$ajax.getDoctorListByDepartment({
        departmentId: this.applyForm.departmentId,
        isExpert: 1,
      }).then((res) => {
        this.doctorList = res.data;
      });
    },
    backTo() {
      this.$emit('back');
      this.$router.replace({
        path: '/remoteConsult/myConsult',
        query: {

        },
      });
    },
    openHistory() {
      // 校验身份证格式
      if (!this.applyForm.patientIdcard) {
        this.$message.error('请输入身份证号');
        return;
      }
      // 校验格式 正则
      const regex = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
      const isPass = regex.test(this.applyForm.patientIdcard);
      if (!isPass) {
        this.$message.error('请输入正确的身份证号');
        return;
      }
      this.$ajax.getPatientInfoByIdCard({
        idCard: this.applyForm.patientIdcard,
      }).then((res) => {
        this.setPatientInfo(res);
      });
    },
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const params = {
            ...this.applyForm,
            diagnosis: this.applyForm.diagnosis.map(item => item.diagnosis).join(','),
            diagnosisJson: JSON.stringify(this.applyForm.diagnosis),
            files: this.imageUrl.join(','),
          };
          delete params.departmentId;
          this.$ajax.addConsultation(params).then(() => {
            this.$message.success('提交成功');
            if (this.isComponent) {
              this.$emit('close');
            } else {
              this.$router.back();
            }
          }).catch((err) => {
            this.$message.error(err.msg);
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
* {
  box-sizing: border-box;
}
#applyConsult {
  .history-box {
    cursor: pointer;
    border: 1px solid;
  }
  background-color: #ffffff;
  padding: 20px;
  border-radius: 16px;
}
</style>
